package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:24097
 * Date:2025-10-12
 * Time:14:08
 */
public class UdpEchoClient {
    private DatagramSocket socket=null;

    private String serverIp;

    private int serverPort;

    //指定访问的服务器地址
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        this.serverIp=serverIp;
        this.serverPort=serverPort;
        socket=new DatagramSocket(9111);
    }

    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while (true){
            //1.读取用户信息
            System.out.println("请输入要发送的内容");
            if(!scanner.hasNext()){
                break;
            }
            String request=scanner.next();
            //2.把请求发送给服务器
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            //3.发送数据包
            socket.send(requestPacket);
            //4.接收服务器响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //5.从服务器读取的数据进行解析,打印出来.
            String response=new String(responsePacket.getData(),0,requestPacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
